package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResult;
import com.jixi.common.result.Result;
import com.jixi.common.utils.Md5Util;
import com.jixi.mapper.AccountMapper;
import com.jixi.mapper.CooperateSchoolCompanyMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.mapper.SchoolMapper;
import com.jixi.pojo.dto.SchoolRegisterDto;
import com.jixi.pojo.entity.Account;
import com.jixi.pojo.entity.CooperateSchoolCompany;
import com.jixi.pojo.entity.Education;
import com.jixi.pojo.entity.School;
import com.jixi.service.SchoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {
	
	@Autowired
	private SchoolMapper schoolMapper;
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private CooperateSchoolCompanyMapper cooperateSchoolCompanyMapper;
	
	@Autowired
	private AccountMapper accountMapper;
	
	/**
	 * 学校注册
	 *
	 * @param schoolRegisterDto 注册信息
	 * @return 注册结果
	 */
	@Override
	public Result schoolRegister(SchoolRegisterDto schoolRegisterDto) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		School school = new School();
		BeanUtils.copyProperties(schoolRegisterDto, school);
		log.info("注册信息：{}", school);
		school.setIsDeleted(0);
		school.setSchoolPassword(Md5Util.getMD5String(school.getSchoolPassword()));
		schoolMapper.insert(school);
		return Result.success("注册成功");
	}
	
	/**
	 * 学校列表
	 *
	 * @param pageNum       页码
	 * @param pageSize      每页数量
	 * @param schoolName    学校名
	 * @param principalName 负责人名
	 * @param status        状态
	 * @return 学校列表
	 */
	@Override
	public Result<PageResult> schoolPage(
			Integer pageNum,
			Integer pageSize,
			String schoolName,
			String principalName,
			Integer status
	) {
		//分页构造器
		Page<School> pageInfo = new Page<>(pageNum, pageSize);
		
		//条件构造器
		LambdaQueryWrapper<School> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(School::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.like(schoolName != null && !schoolName.trim().isEmpty(), School::getSchoolName, schoolName);
		queryWrapper.like(principalName != null && !principalName.trim().isEmpty(), School::getPrincipalName, principalName);
		queryWrapper.eq(status != null, School::getStatus, status);
		
		//执行分页查询
		schoolMapper.selectPage(pageInfo, queryWrapper);
		PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
		return Result.success(pageResult);
	}
	
	/**
	 * 学校详情
	 *
	 * @param schoolId 学校id
	 * @return 学校详情
	 */
	@Override
	public School getSchoolInfoById(Long schoolId) {
		//只查未删除的
		LambdaQueryWrapper<School> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(School::getIsDeleted, 0);
		queryWrapper.eq(School::getSchoolId, schoolId);
		School school = schoolMapper.selectOne(queryWrapper);
		return school;
	}
	
	/**
	 * 学校重置密码
	 *
	 * @param schoolId      学校id
	 * @param resetPassword 重置的密码
	 * @return 重置密码结果
	 */
	@Override
	public Result schoolResetPassword(Long schoolId, String resetPassword) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			return Result.fail("权限不足");
		}
		LambdaQueryWrapper<School> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(School::getSchoolId, schoolId);
		//只查未删除的
		queryWrapper1.eq(School::getIsDeleted, 0);
		School school = schoolMapper.selectOne(queryWrapper1);
		school.setSchoolPassword(Md5Util.getMD5String(resetPassword));
		school.setUpdateTime(DateTime.now());
		schoolMapper.insertOrUpdate(school);
		//修改后踢下线
		StpUtil.logout(schoolId);
		return Result.success("重置密码成功");
	}
	
	/**
	 * 学校状态修改
	 *
	 * @param schoolId 学校id
	 * @param status   状态
	 * @return 修改结果
	 */
	@Override
	public Result updateSchoolStatus(Long schoolId, Integer status) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		if (status != 1 && status != 0) {
			return Result.fail("状态值有误");
		}
		
		//执行修改
		LambdaQueryWrapper<School> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(School::getIsDeleted, 0);
		queryWrapper1.eq(School::getSchoolId, schoolId);
		School school = schoolMapper.selectOne(queryWrapper1);
		school.setStatus(status);
		school.setUpdateTime(DateTime.now());
		schoolMapper.insertOrUpdate(school);
		
		//修改相关合作关系的状态为停用
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper2 = new LambdaQueryWrapper<>();
		//查未删除的
		queryWrapper2.eq(CooperateSchoolCompany::getIsDeleted, 0);
		//查正在合作状态的
		queryWrapper2.eq(CooperateSchoolCompany::getStatus, 1);
		queryWrapper2.eq(CooperateSchoolCompany::getSchoolId, schoolId);
		List<CooperateSchoolCompany> cooperateSchoolCompanies = cooperateSchoolCompanyMapper.selectList(queryWrapper2);
		//存在正在合作的合作关系
		if (status == 0 && ! cooperateSchoolCompanies.isEmpty()) {
			log.info(cooperateSchoolCompanies.toString());
			//枚举修改
			for (CooperateSchoolCompany cooperate : cooperateSchoolCompanies) {
				cooperate.setStatus(0);
				cooperate.setUpdateTime(DateTime.now());
				cooperateSchoolCompanyMapper.insertOrUpdate(cooperate);
			}
			return Result.success("状态修改成功，注意：与该学校相关的 " + cooperateSchoolCompanies.size() + " 个合作关系都已停用");
		}
		return Result.success("状态修改成功");
	}
	
	/**
	 * 学校删除
	 *
	 * @param schoolId 学校id
	 * @return 删除结果
	 */
	@Override
	public Result deleteSchoolById(Long schoolId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//先查是否存在合作
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper2.eq(CooperateSchoolCompany::getSchoolId, schoolId);
		Long count = cooperateSchoolCompanyMapper.selectCount(queryWrapper2);
		if (count != 0) {
			return Result.fail("该学校存在 " + count + " 个合作关系，无法删除");
		}
		
		//假删除
		LambdaQueryWrapper<School> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(School::getIsDeleted, 0);
		queryWrapper1.eq(School::getSchoolId, schoolId);
		School school = schoolMapper.selectOne(queryWrapper1);
		school.setIsDeleted(1);
		school.setUpdateTime(DateTime.now());
		schoolMapper.insertOrUpdate(school);
		
		return Result.success("删除成功");
	}
	
	/**
	 * 学校修改入账账户
	 *
	 * @param schoolId  学校id
	 * @param accountId 账户id
	 * @return 修改结果
	 */
	@Override
	public Result updateSchoolAccount(Long schoolId, Long accountId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//先判断账户是否存在
		LambdaQueryWrapper<Account> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(Account::getAccountId, accountId);
		queryWrapper2.eq(Account::getIsDeleted, 0);
		Account account = accountMapper.selectOne(queryWrapper2);
		if (account == null) {
			return Result.fail("该银行账号不存在");
		}
		
		LambdaQueryWrapper<School> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(School::getIsDeleted, 0);
		queryWrapper1.eq(School::getSchoolId, schoolId);
		School school = schoolMapper.selectOne(queryWrapper1);
		school.setAccountId(accountId);
		school.setUpdateTime(DateTime.now());
		schoolMapper.insertOrUpdate(school);
		return Result.success("修改成功");
	}
	
	/**
	 * 统计学校数量
	 *
	 * @return 学校数量
	 */
	@Override
	public Long countSchoolNum() {
		LambdaQueryWrapper<School> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(School::getIsDeleted, 0);
		return schoolMapper.selectCount(queryWrapper);
	}
}
